//
//  NSString+Safe.m
//  Pods
//
//  Created by fy on 16/1/28.
//
//

#import "NSString+Safe.h"
#import "NSArray+WDAdd.h"
#import "NSDictionary+WDAdd.h"

@implementation NSString (Safe)

+ (NSString *)safeStringFromObject:(id)obj
{
    if (obj == nil) {
        return @"";
    }
    if ([obj isKindOfClass:[NSString class]]) {
        return obj;
    } else if ([obj isKindOfClass:[NSNumber class]]) {
        // 防止 double 类型精度丢失，不用 -[NSNumber stringValue] 方法
        static NSNumberFormatter *numberFormatter;
        if (!numberFormatter) {
            numberFormatter = [[NSNumberFormatter alloc] init];
            [numberFormatter setUsesSignificantDigits: YES];
            [numberFormatter setGroupingSeparator:@""];
            [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
        }
        return [numberFormatter stringFromNumber:obj];
    }
    else if([obj isKindOfClass:[NSNull class]]) {
#if FFCRASH_SERVER_NULL == 1 && DEBUG == 1
        NSAssert(NO, @"属性为null,查一下吧");
        return obj;
#else
        return nil;
#endif
    }else if ([obj isKindOfClass:[NSArray class]]) {
        return [(NSArray *)obj jsonStringEncoded];
    } else if ([obj isKindOfClass:[NSDictionary class]]) {
        return [(NSDictionary *)obj jsonStringEncoded];
    } else {
        return [obj description];
    }
}

- (NSString *)safeSubstringFromIndex:(NSUInteger)from {
    if ( from <= 0 ) {
        return [self copy];
    }
    
    if (from < self.length) {
        return [self substringFromIndex:from];
    }
    return @"";
    
}

- (NSString *)safeSubstringToIndex:(NSUInteger)to {
    
    if ( to <= 0 ) {
        return @"";
    }
    
    if (to < self.length) {
        return [self substringToIndex:to];
    } else {
        return [self copy];
    }
}

- (NSString *)safeSubstringWithRange:(NSRange)range {
    NSInteger from = MAX(0,range.location);
    NSInteger length = MIN(range.length, self.length - from);
    if ( length <= 0 ) {
        return @"";
    }
    return [self substringWithRange:NSMakeRange(from, length)];
}

@end
